### Iterators ###

# 1
module Enumerable
  def each_even
    for n in self
      yield n if n % 2 == 0
    end
    self
  end
end

# a bit of test code...
x = (1..9)
x.each_even { |n| puts n }

# 2
module Enumerable
  def each_grouped_by_first_letter
    h = {}
    for item in self
      key = item[0,1].to_s
      h[key] = [] unless h[key]
      h[key].push(item)
    end
    for stuff in h
      yield stuff
    end
    self
  end
end

# a bit of test code...
a = %w(apple banana cherry alice bob carol alpha bravo charlie)
a.each_grouped_by_first_letter { |letter, words| puts "#{letter} : #{words.join(' ')}" }
# should give:
# a : apple alice alpha
# b : banana bob bravo
# c : cherry carol charlie
#
# ... and it does
